<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="flex items-center gap-6">
				<div class="flex items-center gap-2">
					<img id="img-head" src="img/jstu1.webp">
					<span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
				</div>
				<div class="flex items-center gap-2">
					<a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
				</div>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }">
				<span class="iconify" data-icon="mdi:view-dashboard"></span>
				<a @click="$router.push('/admin')">系统管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
				<span class="iconify" data-icon="mdi:account-group"></span>
				<a @click="$router.push('/admin/users')">用户管理</a>
			</div>
			<div class="menu-item active">
				<span class="iconify" data-icon="mdi:volunteer-activism"></span>
				志愿者管理
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
				<span class="iconify" data-icon="mdi:clipboard-list"></span>
				<a @click="$router.push('/admin/projects')">项目管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
				<span class="iconify" data-icon="mdi:calendar-clock"></span>
				<a @click="$router.push('/admin/schedule')">赛程管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/judges' }">
				<span class="iconify" data-icon="mdi:whistle"></span>
				<a @click="$router.push('/admin/judges')">裁判分配</a>
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<!-- 面包屑导航 -->
			<div class="breadcrumb-container">
				<el-breadcrumb separator="/">
					<el-breadcrumb-item :to="{ path: '/admin' }">系统管理</el-breadcrumb-item>
					<el-breadcrumb-item>志愿者管理</el-breadcrumb-item>
					<el-breadcrumb-item>服务记录</el-breadcrumb-item>
				</el-breadcrumb>
			</div>

			<!-- 统计信息卡片 -->
			<div class="statistics-cards">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon total-volunteers">
									<span class="iconify" data-icon="mdi:account-group"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.totalVolunteers || 0 }}</div>
									<div class="stat-label">总志愿者数</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon total-hours">
									<span class="iconify" data-icon="mdi:clock-time-eight"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.totalServiceHours || 0 }}</div>
									<div class="stat-label">总服务时长(h)</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon today-volunteers">
									<span class="iconify" data-icon="mdi:calendar-today"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.todayVolunteers || 0 }}</div>
									<div class="stat-label">今日服务人数</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon excellent-volunteers">
									<span class="iconify" data-icon="mdi:star"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.excellentVolunteers || 0 }}</div>
									<div class="stat-label">优秀志愿者</div>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>

			<!-- 优秀志愿者展示 -->
			<div class="excellent-volunteers-container">
				<el-card class="form-card">
					<template #header>
						<div class="card-header">
							<span class="card-title">
								<span class="iconify" data-icon="mdi:star-circle" style="color: #FFD700;"></span>
								优秀志愿者展示
							</span>
							<el-button type="text" @click="toggleExcellentCollapse">
								<span class="iconify" :data-icon="isExcellentCollapsed ? 'mdi:chevron-down' : 'mdi:chevron-up'"></span>
							</el-button>
						</div>
					</template>
					<el-collapse-transition>
						<div v-show="!isExcellentCollapsed">
							<el-row :gutter="20">
								<el-col :span="6" v-for="(volunteer, index) in excellentVolunteers" :key="index">
									<el-card class="volunteer-card" shadow="hover">
										<div class="volunteer-avatar">
											<img :src="volunteer.avatar || 'img/default-avatar.png'" :alt="volunteer.name">
											<div class="medal-badge">
												<span class="iconify" data-icon="mdi:medal" style="color: #FFD700;"></span>
											</div>
										</div>
										<div class="volunteer-info">
											<h4>{{ volunteer.name }}</h4>
											<p class="department">{{ volunteer.department }}</p>
											<div class="volunteer-stats">
												<span class="stat-item">
													<span class="iconify" data-icon="mdi:clock-time-eight"></span>
													{{ volunteer.serviceHours }}h
												</span>
												<span class="stat-item">
													<span class="iconify" data-icon="mdi:star"></span>
													{{ volunteer.averageScore }}
												</span>
											</div>
										</div>
									</el-card>
								</el-col>
							</el-row>
						</div>
					</el-collapse-transition>
				</el-card>
			</div>

			<!-- 搜索筛选区域 -->
			<div class="search-bar">
				<el-form :inline="true" :model="searchForm" size="small">
					<el-form-item label="志愿者">
						<el-select v-model="searchForm.volunteerId" placeholder="请选择志愿者" clearable filterable style="width: 180px">
							<el-option
								v-for="volunteer in volunteerOptions"
								:key="volunteer.id"
								:label="volunteer.name + ' (' + volunteer.studentId + ')'"
								:value="volunteer.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="志愿部门">
						<el-select v-model="searchForm.department" placeholder="请选择志愿部门" clearable style="width: 150px">
							<el-option label="竞赛组" value="竞赛组"></el-option>
							<el-option label="后勤组" value="后勤组"></el-option>
							<el-option label="宣传组" value="宣传组"></el-option>
							<el-option label="安全组" value="安全组"></el-option>
							<el-option label="医疗组" value="医疗组"></el-option>
							<el-option label="接待组" value="接待组"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="服务状态">
						<el-select v-model="searchForm.status" placeholder="请选择服务状态" clearable style="width: 130px">
							<el-option label="进行中" value="ongoing"></el-option>
							<el-option label="已完成" value="completed"></el-option>
							<el-option label="已取消" value="cancelled"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="服务时间">
						<el-date-picker
							v-model="searchForm.dateRange"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							style="width: 220px"
							value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch" :loading="loading">
							<i class="el-icon-search"></i> 搜索
						</el-button>
						<el-button @click="handleReset">
							<i class="el-icon-refresh"></i> 重置
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 服务记录列表表格 -->
			<div class="table-container">
				<div class="table-header">
					<div class="table-title">服务记录列表</div>
					<div class="table-actions">
						<el-button type="success" size="small" @click="showAddRecordDialog">
							<i class="el-icon-plus"></i> 添加记录
						</el-button>
						<el-button type="info" size="small" @click="exportRecords">
							<i class="el-icon-download"></i> 导出记录
						</el-button>
					</div>
				</div>
				<el-table
					:data="tableData"
					v-loading="loading"
					stripe
					border
					style="width: 100%">
					<el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
					<el-table-column prop="volunteerName" label="志愿者姓名" width="120" align="center"></el-table-column>
					<el-table-column prop="studentId" label="学号" width="120" align="center"></el-table-column>
					<el-table-column prop="department" label="志愿部门" width="100" align="center">
						<template #default="scope">
							<el-tag size="small" :type="getDepartmentTagType(scope.row.department)">
								{{ scope.row.department }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="taskName" label="服务任务" min-width="150" show-overflow-tooltip></el-table-column>
					<el-table-column prop="serviceDate" label="服务日期" width="120" align="center"></el-table-column>
					<el-table-column prop="serviceHours" label="服务时长" width="100" align="center">
						<template #default="scope">
							<span class="service-hours">{{ scope.row.serviceHours }}h</span>
						</template>
					</el-table-column>
					<el-table-column prop="status" label="服务状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getStatusTagType(scope.row.status)" size="small">
								{{ getStatusText(scope.row.status) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="averageScore" label="评价得分" width="100" align="center">
						<template #default="scope">
							<div class="score-display" v-if="scope.row.averageScore">
								<el-rate
									v-model="scope.row.averageScore"
									disabled
									show-score
									text-color="#ff9900"
									score-template="{value}">
								</el-rate>
							</div>
							<span v-else class="no-score">暂无评价</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="280" align="center" fixed="right">
						<template #default="scope">
							<el-button-group size="mini">
								<el-button type="primary" icon="el-icon-view" @click="handleViewDetail(scope.row)">详情</el-button>
								<el-button
									v-if="scope.row.status === 'ongoing'"
									type="success"
									icon="el-icon-check"
									@click="handleCompleteRecord(scope.row)">
									完成
								</el-button>
								<el-button
									type="warning"
									icon="el-icon-star"
									@click="handleEvaluation(scope.row)">
									评价
								</el-button>
								<el-button
									v-if="scope.row.status === 'completed'"
									type="info"
									icon="el-icon-medal"
									@click="handleGenerateCertificate(scope.row)">
									证书
								</el-button>
								<el-button
									type="danger"
									icon="el-icon-delete"
									@click="handleDeleteRecord(scope.row)">
									删除
								</el-button>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pagination.currentPage"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pagination.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pagination.total">
					</el-pagination>
				</div>
			</div>

			<!-- 服务记录详情对话框 -->
			<el-dialog
				title="服务记录详情"
				v-model="detailDialogVisible"
				width="800px"
				:before-close="handleDetailClose">
				<div v-if="currentRecord" class="detail-content">
					<el-descriptions :column="2" border>
						<el-descriptions-item label="记录ID">{{ currentRecord.id }}</el-descriptions-item>
						<el-descriptions-item label="志愿者姓名">{{ currentRecord.volunteerName }}</el-descriptions-item>
						<el-descriptions-item label="学号">{{ currentRecord.studentId }}</el-descriptions-item>
						<el-descriptions-item label="志愿部门">{{ currentRecord.department }}</el-descriptions-item>
						<el-descriptions-item label="联系电话">{{ currentRecord.phone }}</el-descriptions-item>
						<el-descriptions-item label="服务状态">
							<el-tag :type="getStatusTagType(currentRecord.status)">
								{{ getStatusText(currentRecord.status) }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="服务任务" :span="2">{{ currentRecord.taskName }}</el-descriptions-item>
						<el-descriptions-item label="服务日期">{{ currentRecord.serviceDate }}</el-descriptions-item>
						<el-descriptions-item label="服务时长">{{ currentRecord.serviceHours }}小时</el-descriptions-item>
						<el-descriptions-item label="开始时间">{{ currentRecord.startTime }}</el-descriptions-item>
						<el-descriptions-item label="结束时间">{{ currentRecord.endTime }}</el-descriptions-item>
						<el-descriptions-item label="服务地点" :span="2">{{ currentRecord.location }}</el-descriptions-item>
						<el-descriptions-item label="服务内容" :span="2">{{ currentRecord.serviceContent }}</el-descriptions-item>
						<el-descriptions-item label="平均得分" v-if="currentRecord.averageScore">
							<el-rate
								v-model="currentRecord.averageScore"
								disabled
								show-score
								text-color="#ff9900"
								score-template="{value}">
							</el-rate>
						</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{ formatDateTime(currentRecord.createTime) }}</el-descriptions-item>
						<el-descriptions-item label="完成时间" v-if="currentRecord.completeTime">{{ formatDateTime(currentRecord.completeTime) }}</el-descriptions-item>
					</el-descriptions>
				</div>
			</el-dialog>

			<!-- 添加/编辑服务记录对话框 -->
			<el-dialog
				:title="isEditRecord ? '编辑服务记录' : '添加服务记录'"
				v-model="recordDialogVisible"
				width="600px"
				:before-close="handleRecordClose">
				<el-form :model="recordForm" :rules="recordFormRules" ref="recordFormRef" label-width="120px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="志愿者" prop="volunteerId">
								<el-select v-model="recordForm.volunteerId" placeholder="请选择志愿者" style="width: 100%">
									<el-option
										v-for="volunteer in volunteerOptions"
										:key="volunteer.id"
										:label="volunteer.name + ' (' + volunteer.studentId + ')'"
										:value="volunteer.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="志愿部门" prop="department">
								<el-select v-model="recordForm.department" placeholder="请选择志愿部门" style="width: 100%">
									<el-option label="竞赛组" value="竞赛组"></el-option>
									<el-option label="后勤组" value="后勤组"></el-option>
									<el-option label="宣传组" value="宣传组"></el-option>
									<el-option label="安全组" value="安全组"></el-option>
									<el-option label="医疗组" value="医疗组"></el-option>
									<el-option label="接待组" value="接待组"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="服务日期" prop="serviceDate">
								<el-date-picker
									v-model="recordForm.serviceDate"
									type="date"
									placeholder="请选择服务日期"
									style="width: 100%"
									value-format="yyyy-MM-dd">
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="服务时长" prop="serviceHours">
								<el-input-number
									v-model="recordForm.serviceHours"
									:min="0.5"
									:max="24"
									:step="0.5"
									:precision="1"
									placeholder="请输入服务时长"
									style="width: 100%">
								</el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="开始时间" prop="startTime">
								<el-time-picker
									v-model="recordForm.startTime"
									placeholder="请选择开始时间"
									style="width: 100%"
									format="HH:mm"
									value-format="HH:mm">
								</el-time-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="结束时间" prop="endTime">
								<el-time-picker
									v-model="recordForm.endTime"
									placeholder="请选择结束时间"
									style="width: 100%"
									format="HH:mm"
									value-format="HH:mm">
								</el-time-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="服务任务" prop="taskName">
						<el-input v-model="recordForm.taskName" placeholder="请输入服务任务名称"></el-input>
					</el-form-item>
					<el-form-item label="服务地点" prop="location">
						<el-input v-model="recordForm.location" placeholder="请输入服务地点"></el-input>
					</el-form-item>
					<el-form-item label="服务内容" prop="serviceContent">
						<el-input
							v-model="recordForm.serviceContent"
							type="textarea"
							:rows="4"
							placeholder="请详细描述服务内容">
						</el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleRecordClose">取消</el-button>
						<el-button type="primary" @click="saveRecord" :loading="recordLoading">保存</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 志愿者评价对话框 -->
			<el-dialog
				title="志愿者评价"
				v-model="evaluationDialogVisible"
				width="500px"
				:before-close="handleEvaluationClose">
				<el-form :model="evaluationForm" :rules="evaluationFormRules" ref="evaluationFormRef" label-width="100px">
					<el-form-item label="服务评分" prop="score">
						<el-rate
							v-model="evaluationForm.score"
							:colors="['#99A9BF', '#F7BA2A', '#FF9900']"
							:texts="['较差', '一般', '良好', '优秀', '杰出']"
							show-text>
						</el-rate>
					</el-form-item>
					<el-form-item label="评价内容" prop="comment">
						<el-input
							v-model="evaluationForm.comment"
							type="textarea"
							:rows="4"
							placeholder="请输入对志愿者服务的评价">
						</el-input>
					</el-form-item>
					<el-form-item label="评价人" prop="evaluator">
						<el-input v-model="evaluationForm.evaluator" placeholder="请输入评价人姓名"></el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleEvaluationClose">取消</el-button>
						<el-button type="primary" @click="submitEvaluation" :loading="evaluationLoading">提交评价</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 证书生成对话框 -->
			<el-dialog
				title="生成志愿者服务证书"
				v-model="certificateDialogVisible"
				width="800px"
				:before-close="handleCertificateClose">
				<div v-if="currentCertificateRecord" class="certificate-content">
					<!-- 证书预览 -->
					<div class="certificate-preview" ref="certificateRef">
						<div class="certificate-header">
							<h1>志愿者服务证书</h1>
							<div class="certificate-subtitle">Volunteer Service Certificate</div>
						</div>
						<div class="certificate-body">
							<div class="certificate-info">
								<p class="certificate-text">兹证明</p>
								<h2 class="volunteer-name">{{ currentCertificateRecord.volunteerName }}</h2>
								<p class="certificate-text">同学在 {{ currentCertificateRecord.serviceDate }} 期间</p>
								<p class="certificate-text">积极参与校园运动会志愿服务工作</p>
								<p class="certificate-text">担任 {{ currentCertificateRecord.taskName }} 职务</p>
								<p class="certificate-text">服务时长 {{ currentCertificateRecord.serviceHours }} 小时</p>
								<p class="certificate-text">表现优异，贡献突出</p>
							</div>
							<div class="certificate-footer">
								<div class="signature-section">
									<div class="signature-item">
										<div class="signature-line"></div>
										<span>负责人签名</span>
									</div>
									<div class="signature-item">
										<div class="signature-line"></div>
										<span>颁发日期</span>
									</div>
								</div>
								<div class="certificate-seal">
									<span class="iconify" data-icon="mdi:stamp" style="font-size: 48px; color: #DC143C;"></span>
								</div>
							</div>
						</div>
					</div>

					<!-- 证书设置 -->
					<div class="certificate-settings">
						<h4>证书设置</h4>
						<el-form :model="certificateForm" label-width="100px" size="small">
							<el-row :gutter="20">
								<el-col :span="12">
									<el-form-item label="证书模板">
										<el-select v-model="certificateForm.template" style="width: 100%">
											<el-option label="经典模板" value="classic"></el-option>
											<el-option label="现代模板" value="modern"></el-option>
											<el-option label="简约模板" value="simple"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="证书编号">
										<el-input v-model="certificateForm.certificateNo" placeholder="自动生成" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="12">
									<el-form-item label="颁发单位">
										<el-input v-model="certificateForm.issuer" placeholder="请输入颁发单位"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="颁发日期">
										<el-date-picker
											v-model="certificateForm.issueDate"
											type="date"
											placeholder="选择颁发日期"
											style="width: 100%"
											value-format="yyyy-MM-dd">
										</el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
							<el-form-item label="备注">
								<el-input
									v-model="certificateForm.remarks"
									type="textarea"
									:rows="2"
									placeholder="请输入备注信息">
								</el-input>
							</el-form-item>
							<el-form-item label="包含内容">
								<el-checkbox-group v-model="certificateForm.includes">
									<el-checkbox label="photo">志愿者照片</el-checkbox>
									<el-checkbox label="qrcode">二维码</el-checkbox>
									<el-checkbox label="stats">统计数据</el-checkbox>
									<el-checkbox label="seal">电子印章</el-checkbox>
								</el-checkbox-group>
							</el-form-item>
						</el-form>
					</div>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleCertificateClose">取消</el-button>
						<el-button type="info" @click="previewCertificate">预览</el-button>
						<el-button type="primary" @click="generateCertificate" :loading="certificateLoading">
							<i class="el-icon-download"></i> 生成证书
						</el-button>
					</div>
				</template>
			</el-dialog>
		</main>
	</div>
</template>

<script>
import {
	getAllServiceRecords,
	getVolunteerStatistics,
	getVolunteerRankingStatistics,
	addServiceRecord,
	updateServiceRecord,
	deleteServiceRecord,
	exportServiceRecords,
	submitVolunteerEvaluation,
	searchVolunteers
} from '@/api/volunteer'
import { useAuthStore } from '@/stores/auth'

export default {
	name: 'VolunteerServiceRecords',
	setup() {
		const authStore = useAuthStore()
		return {
			authStore
		}
	},
	data() {
		return {
			// 当前用户信息
			currentUser: null,

			// 统计信息
			statistics: {
				totalVolunteers: 0,
				totalServiceHours: 0,
				todayVolunteers: 0,
				excellentVolunteers: 0
			},

			// 优秀志愿者展示
			isExcellentCollapsed: false,
			excellentVolunteers: [],

			// 志愿者选项
			volunteerOptions: [],

			// 搜索表单
			searchForm: {
				volunteerId: '',
				department: '',
				status: '',
				dateRange: []
			},

			// 表格数据
			tableData: [],
			loading: false,

			// 分页信息
			pagination: {
				currentPage: 1,
				pageSize: 10,
				total: 0
			},

			// 详情对话框
			detailDialogVisible: false,
			currentRecord: null,

			// 添加/编辑记录对话框
			recordDialogVisible: false,
			isEditRecord: false,
			recordLoading: false,
			recordForm: {
				id: null,
				volunteerId: '',
				department: '',
				serviceDate: '',
				serviceHours: 2,
				startTime: '',
				endTime: '',
				taskName: '',
				location: '',
				serviceContent: ''
			},
			recordFormRules: {
				volunteerId: [
					{ required: true, message: '请选择志愿者', trigger: 'change' }
				],
				department: [
					{ required: true, message: '请选择志愿部门', trigger: 'change' }
				],
				serviceDate: [
					{ required: true, message: '请选择服务日期', trigger: 'change' }
				],
				serviceHours: [
					{ required: true, message: '请输入服务时长', trigger: 'blur' }
				],
				startTime: [
					{ required: true, message: '请选择开始时间', trigger: 'change' }
				],
				endTime: [
					{ required: true, message: '请选择结束时间', trigger: 'change' }
				],
				taskName: [
					{ required: true, message: '请输入服务任务名称', trigger: 'blur' }
				],
				location: [
					{ required: true, message: '请输入服务地点', trigger: 'blur' }
				],
				serviceContent: [
					{ required: true, message: '请输入服务内容', trigger: 'blur' }
				]
			},

			// 评价对话框
			evaluationDialogVisible: false,
			evaluationLoading: false,
			currentEvaluationRecord: null,
			evaluationForm: {
				score: 5,
				comment: '',
				evaluator: ''
			},
			evaluationFormRules: {
				score: [
					{ required: true, message: '请给出评分', trigger: 'change' }
				],
				comment: [
					{ required: true, message: '请输入评价内容', trigger: 'blur' },
					{ min: 10, max: 500, message: '评价内容长度在 10 到 500 个字符', trigger: 'blur' }
				],
				evaluator: [
					{ required: true, message: '请输入评价人姓名', trigger: 'blur' }
				]
			},

			// 证书生成对话框
			certificateDialogVisible: false,
			certificateLoading: false,
			currentCertificateRecord: null,
			certificateRef: null,
			certificateForm: {
				template: 'classic',
				certificateNo: '',
				issuer: '校园运动会组委会',
				issueDate: new Date().toISOString().split('T')[0],
				remarks: '',
				includes: ['photo', 'seal']
			}
		}
	},

	created() {
		// 获取当前用户信息
		this.currentUser = this.authStore.userInfo || JSON.parse(localStorage.getItem('user'))
		// 加载数据
		this.loadData()
		this.loadStatistics()
		this.loadVolunteerOptions()
		this.loadExcellentVolunteers()
	},

	methods: {
		// 加载服务记录数据
		async loadData() {
			this.loading = true
			try {
				const params = {
					...this.searchForm,
					currentPage: this.pagination.currentPage,
					pageSize: this.pagination.pageSize
				}

				// 处理日期范围
				if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
					params.startDate = this.searchForm.dateRange[0]
					params.endDate = this.searchForm.dateRange[1]
				}

				const response = await getAllServiceRecords(this.pagination.currentPage, this.pagination.pageSize, params)

				if (response.code === 200) {
					this.tableData = response.data.records || []
					this.pagination.total = response.data.total || 0
				} else {
					this.$message.error(response.message || '获取数据失败')
				}
			} catch (error) {
				console.error('获取服务记录失败:', error)
				this.$message.error('获取数据失败')
			} finally {
				this.loading = false
			}
		},

		// 加载统计信息
		async loadStatistics() {
			try {
				const response = await getVolunteerStatistics()
				if (response.code === 200) {
					this.statistics = {
						totalVolunteers: response.data.totalVolunteers || 0,
						totalServiceHours: response.data.totalServiceHours || 0,
						todayVolunteers: response.data.todayVolunteers || 0,
						excellentVolunteers: response.data.excellentVolunteers || 0
					}
				}
			} catch (error) {
				console.error('获取统计信息失败:', error)
			}
		},

		// 加载志愿者选项
		async loadVolunteerOptions() {
			try {
				const response = await searchVolunteers({ status: 'approved' })
				if (response.code === 200) {
					this.volunteerOptions = response.data || []
				}
			} catch (error) {
				console.error('获取志愿者列表失败:', error)
			}
		},

		// 加载优秀志愿者
		async loadExcellentVolunteers() {
			try {
				const response = await getVolunteerRankingStatistics({ limit: 8, sortBy: 'serviceHours' })
				if (response.code === 200) {
					this.excellentVolunteers = response.data.slice(0, 8).map(volunteer => ({
						...volunteer,
						avatar: volunteer.avatar || 'img/default-avatar.png'
					}))
				}
			} catch (error) {
				console.error('获取优秀志愿者失败:', error)
				// 使用模拟数据作为备用
				this.excellentVolunteers = [
					{ name: '张三', department: '后勤组', serviceHours: 32, averageScore: 4.8, avatar: 'img/avatar1.jpg' },
					{ name: '李四', department: '竞赛组', serviceHours: 28, averageScore: 4.9, avatar: 'img/avatar2.jpg' },
					{ name: '王五', department: '宣传组', serviceHours: 25, averageScore: 4.7, avatar: 'img/avatar3.jpg' },
					{ name: '赵六', department: '安全组', serviceHours: 30, averageScore: 4.8, avatar: 'img/avatar4.jpg' }
				]
			}
		},

		// 切换优秀志愿者展示折叠状态
		toggleExcellentCollapse() {
			this.isExcellentCollapsed = !this.isExcellentCollapsed
		},

		// 搜索
		handleSearch() {
			this.pagination.currentPage = 1
			this.loadData()
		},

		// 重置搜索
		handleReset() {
			this.searchForm = {
				volunteerId: '',
				department: '',
				status: '',
				dateRange: []
			}
			this.handleSearch()
		},

		// 分页大小改变
		handleSizeChange(val) {
			this.pagination.pageSize = val
			this.loadData()
		},

		// 当前页改变
		handleCurrentChange(val) {
			this.pagination.currentPage = val
			this.loadData()
		},

		// 查看详情
		handleViewDetail(row) {
			this.currentRecord = { ...row }
			this.detailDialogVisible = true
		},

		// 显示添加记录对话框
		showAddRecordDialog() {
			this.isEditRecord = false
			this.recordForm = {
				id: null,
				volunteerId: '',
				department: '',
				serviceDate: '',
				serviceHours: 2,
				startTime: '',
				endTime: '',
				taskName: '',
				location: '',
				serviceContent: ''
			}
			this.recordDialogVisible = true
		},

		// 保存记录
		saveRecord() {
			this.$refs.recordFormRef.validate(async (valid) => {
				if (valid) {
					this.recordLoading = true
					try {
						let response
						if (this.isEditRecord) {
							response = await updateServiceRecord(this.recordForm)
						} else {
							response = await addServiceRecord(this.recordForm)
						}

						if (response.code === 200) {
							this.$message.success(`${this.isEditRecord ? '更新' : '添加'}成功`)
							this.recordDialogVisible = false
							this.loadData()
							this.loadStatistics()
						} else {
							this.$message.error(response.message || `${this.isEditRecord ? '更新' : '添加'}失败`)
						}
					} catch (error) {
						console.error(`${this.isEditRecord ? '更新' : '添加'}记录失败:`, error)
						this.$message.error(`${this.isEditRecord ? '更新' : '添加'}失败`)
					} finally {
						this.recordLoading = false
					}
				}
			})
		},

		// 完成记录
		handleCompleteRecord(row) {
			this.$confirm('确定要完成这条服务记录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await updateServiceRecord({
						...row,
						status: 'completed',
						completeTime: new Date().toISOString()
					})
					if (response.code === 200) {
						this.$message.success('记录已完成')
						this.loadData()
					} else {
						this.$message.error(response.message || '操作失败')
					}
				} catch (error) {
					console.error('完成记录失败:', error)
					this.$message.error('操作失败')
				}
			})
		},

		// 删除记录
		handleDeleteRecord(row) {
			this.$confirm('确定要删除这条服务记录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await deleteServiceRecord(row.id)
					if (response.code === 200) {
						this.$message.success('删除成功')
						this.loadData()
						this.loadStatistics()
					} else {
						this.$message.error(response.message || '删除失败')
					}
				} catch (error) {
					console.error('删除记录失败:', error)
					this.$message.error('删除失败')
				}
			})
		},

		// 评价志愿者
		handleEvaluation(row) {
			this.currentEvaluationRecord = row
			this.evaluationForm = {
				score: 5,
				comment: '',
				evaluator: this.currentUser?.realName || '管理员'
			}
			this.evaluationDialogVisible = true
		},

		// 提交评价
		submitEvaluation() {
			this.$refs.evaluationFormRef.validate(async (valid) => {
				if (valid) {
					this.evaluationLoading = true
					try {
						const evaluationData = {
							taskId: this.currentEvaluationRecord.id,
							score: this.evaluationForm.score,
							comment: this.evaluationForm.comment,
							evaluator: this.evaluationForm.evaluator
						}

						const response = await submitVolunteerEvaluation(this.currentEvaluationRecord.id, evaluationData)
						if (response.code === 200) {
							this.$message.success('评价提交成功')
							this.evaluationDialogVisible = false
							this.loadData()
						} else {
							this.$message.error(response.message || '评价提交失败')
						}
					} catch (error) {
						console.error('提交评价失败:', error)
						this.$message.error('评价提交失败')
					} finally {
						this.evaluationLoading = false
					}
				}
			})
		},

		// 导出记录
		async exportRecords() {
			try {
				const params = { ...this.searchForm }
				if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
					params.startDate = this.searchForm.dateRange[0]
					params.endDate = this.searchForm.dateRange[1]
				}

				const response = await exportServiceRecords(params)

				// 创建下载链接
				const url = window.URL.createObjectURL(new Blob([response]))
				const link = document.createElement('a')
				link.href = url
				link.setAttribute('download', `志愿者服务记录_${new Date().toLocaleDateString()}.xlsx`)
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				window.URL.revokeObjectURL(url)

				this.$message.success('导出成功')
			} catch (error) {
				console.error('导出失败:', error)
				this.$message.error('导出失败')
			}
		},

		// 关闭详情对话框
		handleDetailClose() {
			this.detailDialogVisible = false
			this.currentRecord = null
		},

		// 关闭记录对话框
		handleRecordClose() {
			this.recordDialogVisible = false
			this.$refs.recordFormRef.resetFields()
		},

		// 关闭评价对话框
		handleEvaluationClose() {
			this.evaluationDialogVisible = false
			this.currentEvaluationRecord = null
			this.$refs.evaluationFormRef.resetFields()
		},

		// 生成证书
		handleGenerateCertificate(row) {
			this.currentCertificateRecord = row
			this.certificateForm.certificateNo = this.generateCertificateNumber()
			this.certificateForm.issueDate = new Date().toISOString().split('T')[0]
			this.certificateDialogVisible = true
		},

		// 生成证书编号
		generateCertificateNumber() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, '0')
			const day = String(now.getDate()).padStart(2, '0')
			const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
			return `VOL${year}${month}${day}${random}`
		},

		// 生成证书PDF
		generateCertificate() {
			this.certificateLoading = true
			try {
				// 这里应该调用生成证书的API
				// const certificateData = {
				//   recordId: this.currentCertificateRecord.id,
				//   template: this.certificateForm.template,
				//   certificateNo: this.certificateForm.certificateNo,
				//   issuer: this.certificateForm.issuer,
				//   issueDate: this.certificateForm.issueDate,
				//   remarks: this.certificateForm.remarks,
				//   includes: this.certificateForm.includes
				// }
				// const response = await generateVolunteerCertificate(certificateData)

				// 模拟生成证书
				this.downloadCertificate()
				this.$message.success('证书生成成功')
				this.certificateDialogVisible = false
			} catch (error) {
				console.error('生成证书失败:', error)
				this.$message.error('证书生成失败')
			} finally {
				this.certificateLoading = false
			}
		},

		// 下载证书
		downloadCertificate() {
			// 使用html2canvas和jsPDF生成证书PDF
			// 这里简化处理，实际应该使用专业的证书生成库
			const certificateElement = this.certificateRef
			if (!certificateElement) return

			// 创建下载链接
			const link = document.createElement('a')
			link.download = `志愿者服务证书_${this.currentCertificateRecord.volunteerName}_${this.certificateForm.certificateNo}.pdf`

			// 这里应该生成实际的PDF文件
			// 简化处理，创建一个假的下载链接
			const blob = new Blob(['证书内容'], { type: 'application/pdf' })
			link.href = URL.createObjectURL(blob)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			URL.revokeObjectURL(link.href)
		},

		// 预览证书
		previewCertificate() {
			// 打开新窗口预览证书
			const printWindow = window.open('', '_blank')
			if (printWindow) {
				const certificateHTML = this.certificateRef.innerHTML
				printWindow.document.write(`
					<html>
						<head>
							<title>证书预览</title>
							<style>
								body { margin: 0; padding: 20px; font-family: 'SimSun', serif; }
								@media print { body { margin: 0; } }
							</style>
						</head>
						<body>
							${certificateHTML}
						</body>
					</html>
				`)
				printWindow.document.close()
			}
		},

		// 关闭证书对话框
		handleCertificateClose() {
			this.certificateDialogVisible = false
			this.currentCertificateRecord = null
			this.certificateForm = {
				template: 'classic',
				certificateNo: '',
				issuer: '校园运动会组委会',
				issueDate: new Date().toISOString().split('T')[0],
				remarks: '',
				includes: ['photo', 'seal']
			}
		},

		// 退出登录
		handleLogout() {
			this.$confirm('确定要退出登录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				// 使用Pinia的logout方法
				this.authStore.logout()
				// 跳转到登录页
				this.$router.push('/login')
			})
		},

		// 获取状态标签类型
		getStatusTagType(status) {
			const typeMap = {
				'ongoing': 'warning',
				'completed': 'success',
				'cancelled': 'danger'
			}
			return typeMap[status] || 'info'
		},

		// 获取状态文本
		getStatusText(status) {
			const textMap = {
				'ongoing': '进行中',
				'completed': '已完成',
				'cancelled': '已取消'
			}
			return textMap[status] || '未知'
		},

		// 获取部门标签类型
		getDepartmentTagType(department) {
			const typeMap = {
				'竞赛组': 'primary',
				'后勤组': 'success',
				'宣传组': 'warning',
				'安全组': 'danger',
				'医疗组': 'info',
				'接待组': 'primary'
			}
			return typeMap[department] || 'info'
		},

		// 格式化日期时间
		formatDateTime(dateTime) {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		}
	}
}
</script>

<style scoped>
/* 基础样式 */
* {
	font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
	background-color: #f0f2f5;
	color: #1a1a1a;
	margin: 0;
}

/* 容器布局 */
.app-container {
	max-width: 1440px;
	margin: 0 auto;
	display: grid;
	grid-template-columns: 240px 1fr;
	grid-template-rows: 64px 1fr;
	min-height: 100vh;
	background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
	grid-column: 1 / -1;
	background-color: #2C5AA0;
	display: flex;
	align-items: center;
	padding: 0 24px;
}

.logo {
	font-size: 18px;
	font-weight: bold;
	color: white;
	display: flex;
	align-items: center;
	gap: 8px;
}

.flex-grow {
	flex-grow: 1;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.gap-6 {
	gap: 24px;
}

.gap-2 {
	gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
	background-color: white;
	padding: 16px 0;
	border-right: 1px solid #e4e7ed;
}

.menu-item {
	padding: 12px 24px;
	color: #555;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.3s;
	cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
	background-color: #e8eff9;
	color: #2C5AA0;
	border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
	padding: 24px;
	display: grid;
	grid-template-rows: auto auto auto auto 1fr;
	gap: 20px;
	overflow-y: auto;
}

/* 面包屑导航 */
.breadcrumb-container {
	background: white;
	padding: 16px 24px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
}

/* 统计卡片 */
.statistics-cards {
	margin-bottom: 0;
}

.stat-card {
	cursor: pointer;
	transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-content {
	display: flex;
	align-items: center;
	gap: 16px;
}

.stat-icon {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-size: 24px;
}

.stat-icon.total-volunteers {
	background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.total-hours {
	background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.today-volunteers {
	background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.excellent-volunteers {
	background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-info {
	flex: 1;
}

.stat-value {
	font-size: 28px;
	font-weight: bold;
	color: #1f2937;
	line-height: 1;
}

.stat-label {
	font-size: 14px;
	color: #6b7280;
	margin-top: 4px;
}

/* 优秀志愿者展示 */
.excellent-volunteers-container {
	margin-bottom: 0;
}

.form-card .card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.card-title {
	font-weight: 600;
	color: #1f2937;
	display: flex;
	align-items: center;
	gap: 8px;
}

.volunteer-card {
	text-align: center;
	padding: 16px;
	margin-bottom: 16px;
}

.volunteer-avatar {
	position: relative;
	margin-bottom: 12px;
}

.volunteer-avatar img {
	width: 80px;
	height: 80px;
	border-radius: 50%;
	object-fit: cover;
	border: 3px solid #fff;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.medal-badge {
	position: absolute;
	top: -5px;
	right: 15px;
	background: white;
	border-radius: 50%;
	width: 24px;
	height: 24px;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.volunteer-info h4 {
	margin: 8px 0 4px 0;
	color: #1f2937;
	font-weight: 600;
}

.volunteer-info .department {
	color: #6b7280;
	font-size: 14px;
	margin: 0 0 8px 0;
}

.volunteer-stats {
	display: flex;
	justify-content: center;
	gap: 16px;
}

.volunteer-stats .stat-item {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 14px;
	color: #6b7280;
}

/* 搜索区域 */
.search-bar {
	background: white;
	padding: 24px;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	margin-bottom: 0;
}

/* 表格容器 */
.table-container {
	background: white;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	padding: 24px;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.table-title {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
}

.table-actions {
	display: flex;
	gap: 8px;
}

.service-hours {
	font-weight: 600;
	color: #10b981;
}

.score-display {
	display: flex;
	align-items: center;
}

.no-score {
	color: #9ca3af;
	font-size: 12px;
}

/* 分页容器 */
.pagination-container {
	margin-top: 20px;
	text-align: right;
}

/* 详情内容 */
.detail-content {
	padding: 16px 0;
}

/* 头像和退出登录 */
#img-head {
	height: 40px;
	width: 40px;
	border-radius: 50px;
}

.denglu {
	color: white;
	font-size: 15px;
	text-decoration: none;
}

.denglu:hover {
	color: #F44346;
}

.text-sm {
	font-size: 14px;
}

.text-white {
	color: white;
}

/* 证书样式 */
.certificate-content {
	max-height: 600px;
	overflow-y: auto;
}

.certificate-preview {
	border: 2px solid #ddd;
	border-radius: 8px;
	padding: 20px;
	margin-bottom: 20px;
	background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	font-family: 'SimSun', '宋体', serif;
}

.certificate-header {
	text-align: center;
	margin-bottom: 30px;
	border-bottom: 3px double #2C5AA0;
	padding-bottom: 20px;
}

.certificate-header h1 {
	font-size: 32px;
	color: #2C5AA0;
	margin: 0 0 10px 0;
	font-weight: bold;
	letter-spacing: 4px;
}

.certificate-subtitle {
	font-size: 16px;
	color: #666;
	font-style: italic;
	letter-spacing: 2px;
}

.certificate-body {
	min-height: 300px;
}

.certificate-info {
	text-align: center;
	margin-bottom: 40px;
}

.certificate-text {
	font-size: 18px;
	line-height: 1.8;
	color: #333;
	margin: 10px 0;
}

.volunteer-name {
	font-size: 28px;
	font-weight: bold;
	color: #2C5AA0;
	margin: 20px 0;
	text-decoration: underline;
	text-underline-offset: 8px;
}

.certificate-footer {
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
	margin-top: 40px;
	padding-top: 20px;
	border-top: 1px solid #eee;
}

.signature-section {
	display: flex;
	gap: 60px;
}

.signature-item {
	text-align: center;
}

.signature-line {
	width: 120px;
	height: 1px;
	border-bottom: 1px solid #333;
	margin-bottom: 8px;
}

.signature-item span {
	font-size: 14px;
	color: #666;
}

.certificate-seal {
	text-align: right;
	opacity: 0.8;
}

.certificate-settings {
	border-top: 1px solid #eee;
	padding-top: 20px;
}

.certificate-settings h4 {
	margin: 0 0 16px 0;
	color: #333;
}

/* Element UI 样式调整 */
.el-table {
	margin-top: 16px;
}

.el-table th {
	background-color: #fafafa !important;
}

.el-form-item {
	margin-bottom: 0;
}

.el-card {
	border-radius: 8px;
	border: 1px solid #e4e7ed;
}

.el-descriptions {
	margin-top: 16px;
}

.el-descriptions__label {
	font-weight: 600;
}

.el-rate {
	display: flex;
	align-items: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
	.statistics-cards .el-col {
		margin-bottom: 16px;
	}

	.excellent-volunteers-container .el-col {
		margin-bottom: 16px;
	}
}

@media (max-width: 768px) {
	.app-container {
		grid-template-columns: 1fr;
	}

	.sidebar {
		display: none;
	}

	.table-header {
		flex-direction: column;
		gap: 12px;
		align-items: flex-start;
	}

	.table-actions {
		width: 100%;
		justify-content: flex-start;
	}

	.volunteer-stats {
		flex-direction: column;
		gap: 8px;
	}
}
</style>